<template>
  <div class="animation-page">
    <a-tabs v-model:activeKey="activeKey" class="animation-tabs">
      <a-tab-pane key="1" tab="常用算法动画">
        <div class="algorithm-selector">
          <div class="algorithm-scroll-menu">
            <div 
              class="scroll-container"
              @wheel.prevent="handleWheel"
              ref="scrollContainer"
            >
              <div 
                v-for="algorithm in algorithms" 
                :key="algorithm.value"
                :class="['algorithm-item', { active: selectedAlgorithm === algorithm.value }]"
                @click="selectAlgorithm(algorithm.value)"
              >
                {{ algorithm.label }}
              </div>
            </div>
          </div>
          
          <div v-if="selectedAlgorithm" class="animation-display">
            <h3>{{ getAlgorithmName(selectedAlgorithm) }} 动画演示</h3>
            <div class="animation-container">
              <!-- 根据选中的算法显示对应的组件 -->
              <div v-if="selectedAlgorithm === 'truthTable'">
                <TruthTable />
              </div>
              <!-- 其他算法的占位符 -->
              <div v-else class="graph-container">
                <div class="graph-placeholder">
                  <p>算法动画可视化区域</p>
                  <p>当前选中: {{ getAlgorithmName(selectedAlgorithm) }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-tab-pane>
      
      <a-tab-pane key="2" tab="AI动画演示生成">
        <div class="custom-animation">
          <h3>根据描述生成动画</h3>
          <a-textarea
            v-model:value="userDescription"
            placeholder="请输入你想要演示的算法或过程描述，例如：演示二分查找在数组[1,3,5,7,9,11,13,15,17,19,21,23]中查找数字7的过程"
            :rows="4"
            style="margin-bottom: 20px;"
          />
          <a-button type="primary" @click="generateAnimation">生成动画</a-button>
          
          <div v-if="generatedAnimation" class="generated-display">
            <h3>生成的动画演示</h3>
            <div class="animation-container">
              <iframe 
                :srcdoc="generatedHTML" 
                style="width: 100%; border: none;"
                sandbox="allow-scripts allow-same-origin"
                ref="animationFrame"
                @load="adjustIframeHeight"
              ></iframe>
            </div>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { loginWithPassword } from '../api/auth';
import TruthTable from '../animation/TruthTable.vue';
import axios from 'axios';

// 创建axios实例用于动画请求
const request = axios.create({
  baseURL: '/api',
  timeout: 600000 // 10分钟超时，因为生成HTML代码需要较长时间
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('jwt_token');
    if (token) {
      config.headers.JWTtoken = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器，统一处理401未授权
request.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('jwt_token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

const activeKey = ref('1');
const selectedAlgorithm = ref(null);
const animationSpeed = ref(5);
const userDescription = ref('');
const generatedAnimation = ref(false);
const generatedSpeed = ref(5);
const generatedHTML = ref(''); // 用于存储后端返回的HTML
const animationFrame = ref(null); // 用于引用iframe元素

// 扩展算法列表，包含更多离散数学常用算法
const algorithms = [
  { value: 'truthTable', label: '真值表', icon: '' },
  { value: 'satSolver', label: 'SAT求解器', icon: '' },
  { value: 'setOperation', label: '集合运算', icon: '' },
  { value: 'warshall', label: 'Warshall算法', icon: '' },
  { value: 'dijkstra', label: 'Dijkstra算法', icon: '' },
  { value: 'minSpanningTree', label: '最小生成树', icon: '' },
  { value: 'huffman', label: 'Huffman算法', icon: '' },
  { value: 'bipartiteGraph', label: '二部图', icon: '' },
  { value: 'sorting', label: '排序算法', icon: '' }
];

const algorithmNames = {
  truthTable: '真值表',
  satSolver: 'SAT求解器',
  setOperation: '集合运算',
  warshall: 'Warshall算法',
  dijkstra: 'Dijkstra算法',
  minSpanningTree: '最小生成树',
  huffman: 'Huffman算法',
  bipartiteGraph: '二部图',
  sorting: '排序算法'
};

const selectAlgorithm = (value) => {
  selectedAlgorithm.value = value;
};

const getAlgorithmName = (key) => {
  return algorithmNames[key] || '';
};

const startAnimation = () => {
  console.log('开始动画:', selectedAlgorithm.value);
  // 这里将实现具体的动画逻辑
};

const pauseAnimation = () => {
  console.log('暂停动画');
  // 这里将实现暂停逻辑
};

const resetAnimation = () => {
  console.log('重置动画');
  // 这里将实现重置逻辑
};

const generateAnimation = async () => {
  if (userDescription.value.trim()) {
    try {
      console.log('开始请求生成动画...', userDescription.value);
      const response = await request.get('/GenerateAnimation', {
        params: { UserPrompt: userDescription.value }
      });
      
      console.log('后端返回的完整响应:', response);
      console.log('响应数据类型:', typeof response.data);
      
      // 检查后端返回格式：可能是统一格式 {code, msg, data} 或直接返回HTML
      if (typeof response.data === 'string') {
        // 后端直接返回HTML字符串
        console.log('后端直接返回HTML，长度:', response.data.length);
        generatedHTML.value = response.data;
        generatedAnimation.value = true;
        console.log('HTML已设置成功');
      } else if (response.data && response.data.code === 1 && response.data.data) {
        // 后端返回统一格式 {code: 1, msg: string, data: HTML}
        console.log('后端返回统一格式，HTML长度:', response.data.data.length);
        generatedHTML.value = response.data.data;
        generatedAnimation.value = true;
        console.log('HTML已设置成功');
      } else {
        console.warn('未知的返回格式');
        const msg = response.data?.msg || '生成动画失败';
        alert(msg);
      }
    } catch (error) {
      console.error('生成动画失败:', error);
      console.error('错误详情:', error.response);
      const msg = error.response?.data?.msg || error.message || '生成动画失败，请稍后再试';
      alert(msg);
    }
  }
};

const startGeneratedAnimation = () => {
  console.log('开始生成的动画');
};

const pauseGeneratedAnimation = () => {
  console.log('暂停生成的动画');
};

const resetGeneratedAnimation = () => {
  console.log('重置生成的动画');
  generatedAnimation.value = false;
  userDescription.value = '';
  generatedHTML.value = ''; // 清空HTML内容
};

const scrollContainer = ref(null);

// 处理鼠标滚轮事件，实现横向滚动
const handleWheel = (e) => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollLeft += e.deltaY;
  }
};

// 动态调整iframe高度
const adjustIframeHeight = () => {
  if (animationFrame.value) {
    try {
      const iframe = animationFrame.value;
      const body = iframe.contentDocument?.body;
      if (body) {
        const height = body.scrollHeight;
        iframe.style.height = `${height}px`;
      }
    } catch (error) {
      console.warn('无法访问iframe内容或调整高度:', error);
    }
  }
};

</script>

<style scoped>

.animation-page {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.animation-tabs {
  overflow: visible;
}

.algorithm-selector h3,
.custom-animation h3 {
  margin-bottom: 16px;
  color: #1890ff;
}

/* 横向滚动菜单样式 */
.algorithm-scroll-menu {
  width: 100%;
  overflow: hidden;
  margin-bottom: 20px;
}

.scroll-container {
  display: flex;
  overflow-x: hidden;
  padding: 10px 0;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
}

.scroll-container::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.algorithm-item {
  flex: 0 0 auto;
  padding: 10px 20px;
  margin-right: 10px;
  background-color: #f5f5f5;
  border-radius: 20px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
  border: 1px solid #d9d9d9;
}

.algorithm-item:hover {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.algorithm-item.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.animation-display,
.generated-display {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fafafa;
}

.animation-container {
  margin-top: 20px;
}

.graph-container {
  height: 400px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.graph-placeholder p {
  text-align: center;
  color: #8c8c8c;
}

.graph-placeholder p:first-child {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}
</style>